package contegor.scire.core.queries;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import contegor.scire.core.Connectable;
import contegor.scire.core.NeedsPrecedent;
import contegor.scire.core.TaskId;
import contegor.scire.core.WithSubsequentsExtensible;

/**
 * Base {@link Query} for all the ones that depends on others and need to be {@link WithSubsequentsExtensible}.
 *
 * @version $Revision$
 * @author  Héctor Cirbián Pousa ($Author$)
 */
public abstract class QueryWithDependenciesAndSubsequentsExtensible<D extends Connectable, I extends Connectable, O extends Connectable> extends QueryWithDependencies<D, I> implements WithSubsequentsExtensible<I, O> {
  private static final long serialVersionUID = -5759560489387381849L;

  protected List<NeedsPrecedent<? super I, O>> subsequents;

  public QueryWithDependenciesAndSubsequentsExtensible(Query<D> dependency) {
    super(dependency);
  }

  @Override
  public QueryWithDependenciesAndSubsequentsExtensible<D, I, O> withIt(NeedsPrecedent<? super I, O> subsequent) {
    if (this.subsequents == null)
      this.subsequents = new LinkedList<NeedsPrecedent<? super I, O>>();
    this.subsequents.add(subsequent);
    return this;
  }

  @Override
  public List<? extends NeedsPrecedent<? super I, O>> getSubsequentTasks() {
    if (this.subsequents == null)
      return Collections.emptyList();
    return this.subsequents;
  }

  @Override
  public void setTaskId(TaskId taskId) {
    super.setTaskId(taskId);
    if (this.subsequents != null)
      for (NeedsPrecedent<?, ?> subsequent : this.subsequents)
        subsequent.setTaskId(taskId.next(true));
  }
}
